﻿using IM.Easy.Core.Extensions;
using IM.Easy.Core.Services;
using IM.Easy.Core.Utils;
using IM.Easy.Entity.System;
using IM.Easy.Infrastructure.Query;
using IM.Easy.SystemServices.Dtos;
using IM.Easy.SystemServices.IServices;
using Mapster;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IM.Easy.SystemServices.Services
{
    /// <summary>
    /// 字典服务
    /// </summary>
    public class DictTypeService(ISqlSugarClient db) : AppServices<SysDictType>(db), IDictTypeService
    {
        /// 添加字典
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<long> AddAsync(DictTypeDto dto)
        {
            var model = dto.Adapt<SysDictType>();
            ValidateUnique(dto);
            return await db.Insertable(model).ExecuteReturnSnowflakeIdAsync();
        }

        /// <summary>
        /// 更新字典
        /// </summary>

        public bool Update(DictTypeDto dto)
        {
            var dictType = dto.Adapt<SysDictType>();
            ValidateUnique(dto);
            return Db.Updateable(dictType)
                     .IgnoreColumns(s => s.IsSystem)
                     .ExecuteCommandHasChange();
        }

        public PageResponse<DictTypeDto> GetList(DictTypeQueryDto query)
        {
            var list = Db.Queryable<SysDictType>();
            var exp = Expressionable.Create<SysDictType>();
            exp = exp.AndIF(query.IsActive.HasValue, s => s.IsActive == query.IsActive.Value)
                     .AndIF(!string.IsNullOrEmpty(query.Name), s => s.Name.Contains(query.Name))
                     .AndIF(!string.IsNullOrEmpty(query.Code), s => s.Code.Contains(query.Code));
            var page = list
                .Where(exp.ToExpression())
                .ToPageListAsync<SysDictType, DictTypeDto>(query);
            return page;
        }

        /// <summary>
        /// 通过编码获取详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DictTypeDto GetById(long id)
        {
            var type = Db.Queryable<SysDictType>().Where(s => s.Id == id).First();
            return type.Adapt<DictTypeDto>();
        }

        /// <summary>
        /// 判断字典组下是否存在数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool HasDictData(long id)
        {
            var result = Context.Queryable<SysDictType>()
                  .InnerJoin<SysDictData>((g, i) => g.Code == i.Group)
                  .Where((g, i) => g.Id == id)
                  .Any();
            return result;
        }


        /// <summary>
        /// 校验唯一性
        /// </summary>
        /// <param name="dto"></param>
        private void ValidateUnique(DictTypeDto dto)
        {
            var duplicate = db.Queryable<SysDictType>().Any(s => dto.Id != s.Id && dto.Code == s.Code);
            if (duplicate)
                ExceptionUtils.ThrowBusinessException($"字典类型{dto.Code}重复");
        }
    }
}
